package ltd.dujiabao.activemq.jms;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import javax.jms.*;

/**
 * @author : DuJiabao
 * @Project : active-mq
 * @Time : 2021/5/4 23:24
 * @Desc :
 */
public class TransactionProducer {
  private static final String ACTIVEMQ_URL = "tcp://192.168.233.133:61616";  // 服务器端口号，地址
  private static final String DESTINATION_NAME = "queue01";  // 目的地名称
  private ActiveMQConnectionFactory activeMQConnectionFactory;
  private Connection connection = null;
  private Session session = null;
  private MessageProducer producer = null;


  @Before
  public void before() throws JMSException {
    activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
    connection = activeMQConnectionFactory.createConnection();
    connection.start();
  }

  /**
   * 生产者自己提交事务。
   *
   * @throws JMSException
   */
  @Test
  public void test1() throws JMSException {
    session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    Queue queue = session.createQueue(DESTINATION_NAME);
    producer = session.createProducer(queue);
    try {
      for (int i = 0; i < 4; i++) {
        TextMessage textMessage = session.createTextMessage(String.valueOf(i));
        producer.send(textMessage);
        if (i == 2) throw new RuntimeException("中间报一些异常");  // 如果中间发生一些异常，事务就没办法提交，那就没办法将所有消息发送
      }
      session.commit();
      System.out.println("消息发送正常");
    } catch (Exception e) {
      System.out.println("发送失败");
      session.rollback();
      e.printStackTrace();
    }
  }


  @After
  public void after() throws JMSException {
    // 关闭资源
    producer.close();
    session.close();
    connection.close();
    System.out.println("资源关闭完毕");
  }


}
